package org.soenea.doitall.domain.command;

import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.impl.Command;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.domain.mapper.LostUpdateException;
import org.dsrg.soenea.service.SingleAppUniqueIdFactory;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.command.exception.CurrentUserInGroupException;
import org.soenea.doitall.domain.command.exception.UserModifiedException;
import org.soenea.doitall.domain.model.group.*;
import org.soenea.doitall.domain.model.user.*;
import org.soenea.doitall.domain.model.user.mapper.*;

public class CreateGroupCommand extends Command {
	public CreateGroupCommand(Helper helper) {
		super(helper);
	}

	@Override
	public void setUp() throws CommandException {
		// TODO Auto-generated method stub		
	}

	@Override
	public void process() throws CommandException {
		long userID=0;
		User user;

		try {
			try {
				userID = (Long)helper.getSessionAttribute("UserID");
				long groupID = (Long)helper.getSessionAttribute("GroupID");

				if (groupID != 0)
					throw new CurrentUserInGroupException("You are already part of a group. You cannot create a new group.");

				String name = helper.getString("name");
				String description = helper.getString("description");
				long version = helper.getLong("version");
				groupID = SingleAppUniqueIdFactory.getMaxId("group", "groupID");

				Group newGroup = new Group(groupID, name, description, 1, null);
				UoW.getCurrent().registerNew(newGroup);

				helper.setSessionAttribute("GroupID", groupID);

				user = UserInputMapper.find(userID);
				user.setGroupID(groupID);
				user.setVersion(version);
				UoW.getCurrent().registerDirty(user);
				UoW.getCurrent().commit();
			} catch (CurrentUserInGroupException e) {
				user = UserInputMapper.find(userID);
				helper.setRequestAttribute("user", user);
				throw e;
			} catch (LostUpdateException e) {
				user = UserInputMapper.find(userID);
				helper.setRequestAttribute("user", user);
				throw new UserModifiedException();
			}
		} catch (CommandException e) {
			throw e;
		} catch (Exception e) {
			throw new CommandException(e);
		}
	}

	@Override
	public void tearDown() throws CommandError {
		// TODO Auto-generated method stub
	}
}
